<template>
	<div>
		<van-nav-bar title="注册" left-arrow @click-left="onClickLeft"/>
		<van-cell-group inset>
			<van-field v-model="email" label="邮箱" placeholder="邮箱" />
			<van-field v-model="code" label="验证码" placeholder="请输入验证码">
				<template #button>
					<van-button size="small" :disabled="count!=60" type="primary"
						@click="getCode">{{codeStr}}</van-button>
				</template>
			</van-field>

			<van-field v-model="username" label="用户名" placeholder="用户名" />
			<van-field v-model="password" type="password" label="密码" placeholder="密码" />
		</van-cell-group>
		<div style="margin: 16px;">
			<van-button round block type="primary" @click="register">
				注册
			</van-button>
		</div>
	</div>
</template>

<script>
	import axios from '../utils/request'
	import {
		Toast
	} from 'vant';
	export default {
		computed: {

		},
		data() {
			return {
				count: 60,
				codeStr: '获取验证码',
				code: '',//验证码
				username: '',//用户名
				password: '',//密码
				email: ""//邮箱
			}
		},
		mounted() {

		},
		methods: {
			onClickLeft(){
				this.$router.back()	
			},
			//获取验证码
			getCode() {
				
				if (this.email == '') {
					Toast.fail('请输入邮箱地址');
					return
				}
				if (this.count != 60) {
					return
				}
				axios.post('/getCode?email=' + this.email)
					.then(response => {//接口返回的数据

							this.counting = true;
							Toast.success("获取验证码成功");
							this.count = 59;
							this.codeStr = '59秒'
							let that = this;
							const countDown = setInterval(() => {
								if (that.count == 0) {
									that.count = 60,
										that.codeStr = '获取验证码'
									clearInterval(countDown);
									return;
								}
								that.count--;
								that.count = that.count,
									that.codeStr = that.count < 10 ? `0${that.count}s` : `${that.count}s`
							}, 1000);


					})
					.catch(error => {
						console.log(error.response);
					});
			},
			countDownEnd() {
				this.counting = false;
			},
			//注册接口
			register() {

				Toast.loading({
					message: '注册中...'
				});
				axios.post('/register', {
						code: this.code,
						username: this.username,
						password: this.password,
						email: this.email
					})
					.then(response => {

							this.$router.back('')//返回上一个页面
							Toast.success("注册成功");


					})
					.catch(error => {
						console.log(error.response);
					});
			}
		}
	}
</script>

<style>
	.captcha-container {
		margin-top: 16px;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.captcha-loading {
		font-size: 12px;
		color: #999;
	}
</style>